from openai import OpenAI
from celery import shared_task
from django.utils import timezone
from spark.models import Subtask
import logging
logger = logging.getLogger(__name__)
logger.info("开始调用 DeepSeek 接口...")


client = OpenAI(api_key="sk-50a3178822814be680a60ba61fdefa78", base_url="https://api.deepseek.com")


# 请根据实际情况导入 deepseek 客户端
# from your_deepseek_module import client
@shared_task
def process_deepseek_task(subtask_id, task_description, file_content):
    subtask = Subtask.objects.get(pk=subtask_id)
    prompt = f"""
您是一位公正的任务审核员。请根据以下信息判断该用户的任务是否完成。
任务描述: {task_description}
用户提交内容: {file_content}

请给出简要评论，并在回答开头用“通过”或“不通过”表明审核是否通过。
例如：
"通过: 该用户表现良好……"
或
"不通过: 该用户提交内容缺少……"
"""
    try:
        print("开始调用 DeepSeek 接口...")
        completion = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "You are a fair performance evaluator."},
                {"role": "user", "content": prompt},
            ],
            stream=False
        )
        analysis = completion.choices[0].message.content.strip()
        print("DeepSeek 返回结果:", analysis)
        subtask.comments = analysis

        if analysis.startswith("通过"):
            pass
        elif analysis.startswith("不通过"):
            subtask.status = 'in_progress'
        else:
            subtask.status = 'in_progress'
        subtask.updated_at = timezone.now()
        subtask.save()
        return analysis
    except Exception as e:
        error_msg = f"DeepSeek 分析出错: {e}"
        print(error_msg)
        subtask.comments = error_msg
        subtask.status = 'in_progress'
        subtask.updated_at = timezone.now()
        subtask.save()
        raise e